﻿using System;
using System.Collections.Generic;


namespace DailyFx.AI
{

	public class MultiMappingMediator : IMediator
	{
		private IDictionary<ITask, ICollection<IExpert>> _mappings = 
			new Dictionary<ITask, ICollection<IExpert>> ();


		public void bind ( ITask task, IExpert expert )
		{

			ICollection<IExpert> experts = null;
			bool ok = this._mappings.TryGetValue( task, out experts );
		   if ( !ok) 
		   {
		      experts = new List<IExpert>();
		      this._mappings.Add ( task, experts );
		   }
			if ( experts.Contains(expert ) )
				throw new ArgumentException ( "Expert is already mapped to task " + task.Label );
		   
			experts.Add ( expert);
		}
   
		public void unbind ( ITask task, IExpert expert )
		{
			ICollection<IExpert> experts = this._mappings[task];

			if ( !experts.Contains(expert))
				throw new ArgumentException("Expert is not mapped to " + task.Label);

		   experts.Remove ( expert);
		   
			if (experts.Count == 0)
			{
		      this._mappings.Remove( task);
		   }
		}
   

		public IReadOnlyCollection<IExpert> mediate ( ITask task)
		{
			ICollection<IExpert> experts = null ;
			bool ok = this._mappings.TryGetValue(task, out experts);
			if (!ok)
			{
				return null;
			}

		   return ( (List<IExpert>)experts ).AsReadOnly() ;
		}
	}

}
